package Users;

import Database.*;
import java.sql.SQLException;

public class Stats {
	private Database DB;

    public Stats() throws Exception {
		DB = new Database();
    }
    
    public String getStatsHtmlForUser(int userID) throws SQLException {
        UserInterface userInterfaceObj = new UserInterface();
		
        Row result = DB.queryRow("SELECT * FROM users WHERE id='"+userID+"'");
        String userDomain = result.getColumnValue("domain");
		
        userInterfaceObj.setUserDomain(result.getColumnValue("domain"));
        userInterfaceObj.setUserName(result.getColumnValue("name"));
        userInterfaceObj.setUserSurname(result.getColumnValue("surname"));
        userInterfaceObj.setLastLoginDate(result.getColumnValue("last_visit"));

        userInterfaceObj.setStatsResetLink("/stats/" + result.getColumnValue("domain") + "/" + result.getColumnValue("password") + "/reset");
		
        Row[] results = DB.queryRows("SELECT * FROM pages WHERE user_domain='"+userDomain+"'");
        String[] filePaths = new String[results.length];
        String[] visits = new String[results.length];

        for (int i = 0; i < results.length; i++) {
            filePaths[i] = results[i].getColumnValue("path");
            visits[i] = results[i].getColumnValue("visits");
        }
		
        userInterfaceObj.setUserFilesTable(filePaths, visits);
		
        DB.query("UPDATE users SET last_visit=CURRENT_DATE WHERE id='"+userID+"'");
		
        return userInterfaceObj.getInterfaceHtml();
    }
	
    public void resetStatsForUser(int userID) throws SQLException {
        Row result = DB.queryRow("SELECT domain FROM users WHERE id='"+userID+"'");
        DB.query("DELETE FROM pages WHERE user_domain='"+result.getColumnValue("domain")+"'");
    }

    //Kvieciam kaskart, kai gaunama ir apdorojama uzklausa kazkokiam puslapiui.
    public void pageRequested(String pageUrl) throws SQLException {
        String path = pageUrl;
        String domain = path.split("\\/")[1];

        if (domain.equals("stats")) {
                return;
        }

        Row result = DB.queryRow("SELECT * FROM pages WHERE path='"+path+"'");
        if (result != null) {
                DB.query("UPDATE pages SET visits=visits+1 WHERE path='"+path+"'");
        } else {
                DB.query("INSERT INTO pages (path, user_domain, visits) VALUES ('"+path+"', '"+domain+"', '1')");
        }
    }
}